/*
 * Copyright (C) 2012 mAPPn.Inc
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.mol.market.ui;

import java.util.ArrayList;
import java.util.HashMap;

import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.FrameLayout;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.mol.market.Constants;
import com.mol.market.R;
import com.mol.market.common.network.ApiAsyncTask;
import com.mol.market.common.network.MarketAPI;
import com.mol.market.common.util.Utils;
import com.mol.market.common.widget.AppListAdapter;
import com.mol.market.common.widget.LoadingDrawable;

/**
 * 精品页
 * @since 0.9.6
 * @author Chaos
 * @date 2012-10-16	
 */
public class HighQualityFragment extends LazyloadListFragment implements 
                OnClickListener,ApiAsyncTask.ApiRequestListener,OnItemClickListener{
    
    private AppListAdapter mRecommendAdapter;
    private FrameLayout mLoading;
    private ProgressBar mProgress;
    private TextView mNoData;
    
    private int mTotalSize;
    
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        return super.onCreateView(inflater, container, savedInstanceState);
    }

    private View doInit(View root){
        mList = (ListView)root.findViewById(android.R.id.list);
        mLoading = (FrameLayout) root.findViewById(R.id.loading);
        mProgress = (ProgressBar) root.findViewById(R.id.progressbar);
        mProgress.setIndeterminateDrawable(new LoadingDrawable(root.getContext()));
        mProgress.setVisibility(View.VISIBLE);
        mNoData = (TextView) root.findViewById(R.id.no_data);
        mNoData.setOnClickListener(this);
        mList.setEmptyView(mLoading);
        return root;
    }
    
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        lazyload();
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        
        super.onActivityCreated(savedInstanceState);
    }

    @Override
    public void onClick(View v) {
        //重试
        mNoData.setVisibility(View.GONE);
        mProgress.setVisibility(View.VISIBLE);
        
        lazyload();
    }
    
    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        switch (parent.getId()) {
        case android.R.id.list:

            // 首页产品列表，去产品详细页 需要考虑Header View所占位置
            @SuppressWarnings("unchecked")
            HashMap<String, Object> item = (HashMap<String, Object>) parent.getAdapter()
                    .getItem(position); 
            String pid = (String) item.get(Constants.KEY_PRODUCT_ID);
            boolean isCpa = (Boolean) item.get(Constants.KEY_PRODUCT_IS_STAR);
            Intent detailIntent = new Intent(getActivity(), com.mol.market.ui_v4.ProductDetailActivity.class);
            detailIntent.putExtra(Constants.EXTRA_PRODUCT_ID, pid);
            
            if (isCpa) {
                // 统计推荐位
                Utils.trackEvent(
                        getActivity(),
                        Constants.GROUP_2,
                        String.format(Constants.EVENT_CLICK_RECOMMEND,
                                item.get(Constants.KEY_PRODUCT_NAME), position));
                detailIntent.putExtra(Constants.EXTRA_PRODUCT_RECOMMEND, true);
            }
            startActivity(detailIntent);
            
            break;

        default:

            break;
        }
    }

    @SuppressWarnings("unchecked")
    @Override
    public void onSuccess(int method, Object obj) {
        switch (method) {
        case MarketAPI.ACTION_GET_RECOMMEND_PRODUCTS:
            
            HashMap<String, Object> result = (HashMap<String, Object>) obj;
            
            if (mTotalSize <= 0) {
                // 获取总大小
                mTotalSize = (Integer) result.get(Constants.KEY_TOTAL_SIZE);
            }
            
            
            mRecommendAdapter.addDataList((ArrayList<HashMap<String, Object>>) result
                    .get(Constants.KEY_PRODUCT_LIST));
            
            setLoadResult(true);
            break;

        default:
            break;
        }
      
    }

    @Override
    public void onError(int method, int statusCode) {
        switch (method) {
        case MarketAPI.ACTION_GET_RECOMMEND_PRODUCTS:
            mNoData.setVisibility(View.VISIBLE);
            mProgress.setVisibility(View.GONE);
            
            setLoadResult(false);
            break;
        }
    }

    @Override
    public void doLazyload() {
        MarketAPI.getRecommendProducts(getActivity(), this, "776",
          getItemsPerPage(), getStartIndex());
    }

    @Override
    public AppListAdapter doInitListAdapter() {
        mRecommendAdapter = new AppListAdapter(
                getActivity(),
                null,
                R.layout.common_product_list_item, 
                new String[] {
                        Constants.KEY_PRODUCT_ICON_URL, 
                        Constants.KEY_PRODUCT_NAME,
                        Constants.KEY_PRODUCT_SUB_CATEGORY, 
                        Constants.KEY_PRODUCT_IS_STAR,
                        Constants.KEY_PRODUCT_SIZE, 
                        Constants.KEY_PRODUCT_DOWNLOAD }, 
                new int[] {
                        R.id.iv_logo, 
                        R.id.tv_name, 
                        R.id.tv_description, 
                        R.id.iv_star,
                        R.id.tv_size, 
                        R.id.tv_download });
        mRecommendAdapter.setActivity(getActivity());
        mRecommendAdapter.setProductList();
        mList.setAdapter(mRecommendAdapter);
        mList.setOnItemClickListener(this);
        return mRecommendAdapter;
    }

    @Override
    public View doInitView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        return doInit(inflater.inflate(R.layout.fragment_highquality, null));
    }
    
    protected int getItemCount() {
        return mTotalSize;
    }

}
